package com.mxbbx.wdn.web.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mxbbx.wdn.domain.menu.Menu;
import com.mxbbx.wdn.domain.role.Role;
import com.mxbbx.wdn.domain.user.User;
import com.mxbbx.wdn.exception.UserNotFoundException;

/**
 * 登录验证控制模块
 * @author 
 *
 */

public class LoginServlet extends BaseServlet {
	
	private static final long serialVersionUID = 7279138098299110478L;
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			login(request,response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private void login(HttpServletRequest request,HttpServletResponse response)
			throws ServletException,IOException, SQLException{
		String path="login.jsp";
		//LOG.info("用户登录");
		try{
			String userId=request.getParameter("userId");
			String password=request.getParameter("password");
			User user=new User(userId,password);
			request.getSession().setAttribute("user",user); //获取session对象,然后把要绑定对象/值 绑定到session对象上
			List list = new ArrayList<List>();//向上转型，<父类型> <引用变量名> = new <子类型>();List是ArrayList的父类
			for(Role role:user.getRoles()){
				for(Menu menu:role.getMenus()){
					String name=menu.getMenuId();
					String value=menu.getMenuId();
					request.getSession().setAttribute(name, value); //获取session对象，绑定菜单编号对象（循环共享菜单编号）
					list.add(name); //存储接收的list菜单编号
					//path="index.jsp";
				}
				request.getSession().setAttribute("list", list);//获取session对象，绑定菜单列表对象
			}
			//绑定行政区域编号和用户名
			request.getSession().setAttribute("agencode", user.getAgencode());
			request.getSession().setAttribute("userName", user.getFullName());
			path="index.jsp";

		}catch(UserNotFoundException e){
			path="login.jsp";
		}
		//跳转页面
		process(request,response,path);
		
	}
		
}



